$("body").addClass('page-sidebar-fixed');
var util = {
	/**
	 * 
	 * @param resUrl
	 * @param params
	 */
	showContent : function(resUrl,params) {
		//页面跳转时，自动刷新标识更新为不刷新
		$("#page-content").empty();
		$("#page-content").load(resUrl,params,function(responseTxt,statusTxt,xhr){
			//创建回调函数消除定时器
			
			if(monitorDetailCount != 0){
				if(monitorRefreshTimer){
					window.clearInterval(monitorRefreshTimer); //清除定时器
				}
			}
			//控制台定时器消除 因需要跳转到详情页面 不能共用定时器
			if(monitorConsoleDetailCount != 0){
				if(monitorConsoleRefreshTimer){
					window.clearInterval(monitorConsoleRefreshTimer);    //清除定时器
				}
			}
			//控制台定时器消除 因需要跳转到详情页面 不能共用定时器
			if(cusmonitorConsoleDetailCount != 0){
				if(cusmonitorConsoleRefreshTimer){
					window.clearInterval(cusmonitorConsoleRefreshTimer); //清除定时器
				}
			}
			//控制台定时器消除 因需要跳转到详情页面 不能共用定时器
			if(overviewRefreshCount != 0){
				if(overviewRefreshTimer){
					window.clearInterval(overviewRefreshTimer); //清除定时器
				}
			}
			//控制台定时器消除 因需要跳转到详情页面 不能共用定时器
			if(overviewColckRefreshCount != 0){
				if(overviewColckRefreshTimer){
					window.clearInterval(overviewColckRefreshTimer); //清除定时器
				}
			}
			//控制台定时器消除 因需要跳转到详情页面 不能共用定时器
			if(alertQueryRefreshCount != 0){
				if(alertQueryRefreshTimer){
					window.clearInterval(alertQueryRefreshTimer); //清除定时器
				}
			}

			//控制台定时器消除 因需要跳转到详情页面 不能共用定时器
			if(board1RefreshCount != 0){
				if(board1RefreshTimer){
					window.clearInterval(board1RefreshTimer); //清除定时器
				}
			}

			//控制台定时器消除 因需要跳转到详情页面 不能共用定时器
			if(board2RefreshCount != 0){
				if(board1RefreshTimer){
					window.clearInterval(board2RefreshTimer); //清除定时器
				}
			}
			//控制台定时器消除 因需要跳转到详情页面 不能共用定时器
			if(board3RefreshCount != 0){
				if(board1RefreshTimer){
					window.clearInterval(board3RefreshTimer); //清除定时器
				}
			}
			//控制台定时器消除 因需要跳转到详情页面 不能共用定时器
			if(board4RefreshCount != 0){
				if(board1RefreshTimer){
					window.clearInterval(board4RefreshTimer); //清除定时器
				}
			}
			
		    monitorDetailCount=1;
		    monitorConsoleDetailCount = 1;
		    cusmonitorConsoleDetailCount = 1;
		    overviewRefreshCount = 1;
		    overviewColckRefreshCount = 1;
		    alertQueryRefreshCount = 1;

		    //看板页面定时器
			board1RefreshCount = 1;
			board2RefreshCount = 1;
			board3RefreshCount = 1;
			board4RefreshCount = 1;
			//按钮权限
		    var pageBtn = btnResource[resUrl];
			for (var index in pageBtn) {
				var btnId = pageBtn[index].btnId;
				$("#" + btnId).show();
			}
		});
		util.setHeight();
	},
	setHeight : function() {
		var height = innerHeight - 76;
		var styleStr = "min-height:" + height + "px;";
		var styleStr1 = "min-height:" + height + "px;";
		$("#page-content").attr("style", styleStr);
		$(".page-content").attr("style", styleStr1);
	},
	/**
	 * 
	 * @returns {___anonymous492_776}
	 */
	getDToLanguage : function() {
		return {
			"sLengthMenu" : "_MENU_",
			"sEmptyTable" : "没有数据",
			"sInfoEmpty" : "显示第 0 至 0 项记录，共 0 项",
			"sInfo" : "显示第 _START_ 至 _END_ 条数据，共 _TOTAL_ 条",
			"sFilter" : false,
			"sProcessing" : "加载中...",
			"oPaginate" : {
				"sPrevious" : "上一页",
				"sNext" : "下一页"
			}
		};
	},
	/**
	 * 
	 * @param title
	 * @param msg
	 * @param fnCall
	 */
	alertMsg : function(title, msg, fnCall) {
		var divId = "alert_parent_div_0009";
		var alertHtml = "";
		alertHtml += '<div id="'
				+ divId
				+ '" href="#alert_div_0009"  data-toggle="modal" style="display:none;">';
		alertHtml += '<div id="alert_div_0009" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel2" aria-hidden="true">';
		alertHtml += '<div class="modal-header">';
		alertHtml += '<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>';
		alertHtml += '<h3 id="myModalLabel2">' + title + '</h3>';
		alertHtml += '</div>';
		alertHtml += '<div class="modal-body">';
		alertHtml += '<p>' + msg + '</p>';
		alertHtml += '</div>';
		alertHtml += '<div class="modal-footer">';
		alertHtml += '<button data-dismiss="modal" class="btn blue">确认</button>';
		alertHtml += '</div>';
		alertHtml += '</div>';
		alertHtml += '</div>';
		if ($("#alert_parent_div_0009")) {
			$("#alert_parent_div_0009").remove();
		}
		$("body").append(alertHtml);
		$("#alert_parent_div_0009").click();
	},
	/**
	 * 
	 * @returns 创建索引列
	 */
	createRowIndex : function(){
		var c = {};
		c.bSortable = false;
		c.render =  function(data, type, full, meta) {
			return meta.row + 1 + meta.settings._iDisplayStart;
		};
		return c;
	},
	
	/**
	 * 根据勾选获取数据
	 * @param tableId table元素id
	 * @returns 选中的 数据数组
	 */
	getCheckedData : function (tableId) {
		var checkboxes = $("#"+ tableId +" tbody").find("input.checkboxes");
		var table = $('#'+ tableId + '').DataTable();
		var dataArray=[];
		var data;
		var row;
		for (var i=0;i<checkboxes.length;i++) {
			var span = $($(checkboxes[i]).parent())[0];
			if (span.classList.contains("checked")) {
				row = table.cell($($(span).parent()).parent()).index().row;
				data = table.data()[row];
				data['rowIndex'] = row;
				dataArray.push(data);
			}
		}
		return dataArray;
	},
	
	/**
	 * 点击table行时自动选中checkbox(checkbox的calss要为checkboxes)
	 * @param tableId tableId
	 */
	checkBoxSelect : function (tableId) {
		$('#'+ tableId +' tbody ').on('click', 'tr', function() {
			var group = $('#'+tableId+' .group-checkable');
			var checkboxes = $("#"+ tableId +" tbody").find("input.checkboxes");
			var boxlength = checkboxes.length;
			if (boxlength>1) {
				group.parent().removeClass("checked");
				group.attr("checked", false);
				group.checked=false;
				for (var i=0;i<boxlength;i++) {
					$(checkboxes[i]).parent().removeClass("checked");
				}
			} else {
				group.parent().addClass("checked");
				group.attr("checked", true);
			}
			var check = $($(this).find("span")[0]);
			check.addClass("checked");
		});
	},
	
	/**
	 * 全选CheckBox change 事件
	 * @param tableId tableId
	 */
	allCheckBoxChange : function (tableId) {
		jQuery('#'+tableId+' .group-checkable').change(function() {
			var set = jQuery(this).attr("data-set");
			var checked = jQuery(this).is(":checked");
			jQuery(set).each(function() {
				if (checked) {
					$(this).parent().attr("class", "checked");
				} else {
					$(this).parent().removeClass("checked");
				}
			});
			jQuery.uniform.update(set);
		});
	},
	
	/**
	 * table勾选复选框关联全选
	 * @param tableId
	 * @param boxSelected
	 */
	selectCheckBox : function(tableId, boxSelected) {
		event.stopPropagation();
		var spanObj=$(boxSelected).children()[0];
		var group = $('#'+tableId+' .group-checkable');
		if ($(spanObj).hasClass('checked')) {
			$(spanObj).removeClass('checked');
			group.parent().removeClass("checked");
			group.attr("checked", false);
		} else {
			$(spanObj).addClass('checked');
			var checkAll = true;
			var checkboxes = $("#"+ tableId +" tbody").find("input.checkboxes");
			for (var i=0;i<checkboxes.length;i++) {
				var span = $($(checkboxes[i]).parent())[0];
				if (!span.classList.contains("checked")) {
					checkAll = false;
					break;
				}
			}
			if (checkAll) {
				group.parent().addClass("checked");
				group.attr("checked", true);
			}
		}
	},
	
	/**
	 * table重新加载后清除check选项
	 * @param tableId
	 */
	clearSelected : function (tableId) {
		var group = $('#'+tableId+' .group-checkable');
		group.parent().removeClass("checked");
		group.attr("checked", false);
	},
	
	/**
	 * 构建dataTables配置
	 * @param url请求地址
	 * @param queryFn 查询方法
	 * @param pageLength  一页显示条数
	 * @param columns 列
	 * @param newConfig 新的配置
	 * @returns dataTables配置
	 */
	dataTableConfig : function(url,queryFn,pageLength,columns,newConfig){
		var config={};
		config = {
				"lengthMenu": [
					             [5, 15, 25, 50],
					             ['5','15','25','50']
					         ],
				"processing" : false,
				"serverSide" : true,
				"sAjaxSource" : url,
				"fnServerData" : queryFn,
				"pageLength" : pageLength,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : {
					"sLengthMenu" : "_MENU_",
					"sEmptyTable" : "没有数据",
					"sInfoEmpty" : "显示第 0 至 0 项记录，共 0 项",
					"sInfo" : "显示第 _START_ 至 _END_ 条数据，共 _TOTAL_ 条",
					"sFilter" : false,
					"sProcessing"  : "加载中...",
					"oPaginate" : {
						"sPrevious" : "上一页",
						"sNext" : "下一页"
					}
				},
				"columns" :columns
		};
		util.apply(config,newConfig);
		return config;
	},
	
	/**
	 * 将c中的属性值循环设定给o中  
	 * @param o 对象1
	 * @param c 对象2
	 * @returns 新的对象1
	 */
	apply : function(o, c){  
	    //将c中的属性值循环设定给o中  
	    if(o && c && typeof c == 'object'){  
	        for(var p in c){  
	            o[p] = c[p];  
	        }  
	    }  
	    return o;  
	},
	
	/**
	 * 初始化checkBox
	 * @param tableId
	 */
	initCheckBox : function(tableId) {
		this.checkBoxSelect(tableId);
		this.allCheckBoxChange(tableId);
		App.initUniform();
	},
	
	/**
	 * 判断字符串是否为空
	 * @param str 要判断的字符串
	 */
	isEmpty : function(str){
		if(str == "" || str == null || str == undefined)
		return true;
		else return false;
	},
	
	/**
     * 
     * @param mis 时间的毫秒数
     * @returns {String}  s时间的格式返回
     */
    getDateStr : function(mis) {
      var unixTimestamp = new Date(mis); 
      var year = unixTimestamp.getFullYear();
      var month = unixTimestamp.getMonth() + 1 <= 9 ? ("0" + (unixTimestamp.getMonth() + 1 )) : unixTimestamp.getMonth() + 1;
      var day = unixTimestamp.getDate()<= 9 ? ("0" + unixTimestamp.getDate()) : unixTimestamp.getDate();
      var hour = unixTimestamp.getHours() <= 9 ? ("0" + unixTimestamp.getHours()) : unixTimestamp.getHours();
      var minute = unixTimestamp.getMinutes() <= 9 ? ("0" + unixTimestamp.getMinutes()) : unixTimestamp.getMinutes();
      var second = unixTimestamp.getSeconds() <= 9 ? ("0" + unixTimestamp.getSeconds()) : unixTimestamp.getSeconds();
      var str = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
      return str;
    },
    
    /**
     * 
     * @param url 后台方法映射地址
     * @param params 参数
     * @param loadingId loading divId
     */
    ajaxDownload:function(url, params, loadingId){
    	if(params) {
    		$.fileDownload(url, {
    			httpMethod: 'POST',
    			data: params,
    			prepareCallback:function(url){
    				
    			},
    			successCallback:function(url){
    				App.unblockUI($(loadingId));//停止loading
    				rmsBox.notify('success', {msg: '操作成功'});
    			},
    			failCallback: function (html, url) {
    				App.unblockUI($(loadingId));//停止loading
    				rmsBox.notify('error', {msg: '操作失败！',delay:3000});
    			}
            });
    	} else {
    		$.fileDownload(url, {
    			httpMethod: 'POST',
    			prepareCallback:function(url){
    				console.log("准备提交");
    			},
    			successCallback:function(url){
    				console.log("操作成功");
    				rmsBox.notify('success', {msg: '操作成功'});
    			},
    			failCallback: function (html, url) {
    				rmsBox.notify('error', {msg: '操作失败！',delay:3000});
    			}
            });
    	}
    },
    
    /**
     * 给指定下拉框赋值
     * @param key 字典parentKey
     * @param selectId 下拉框输入id
     * @param defaultOption 默认选择
     * @param dictUrl 查询方法（非字典值下拉框查询）
     */
    getDictByParentKey:function(key, selectId, defaultOption, dictUrl){
    	var url;
    	if (dictUrl) {
    		url = dictUrl;
    	} else {
    		url = "main/sysDictIndex/getDictByParentKey.mvc";
    	}
    	$.ajax({
			"type" : "post",
			"url" : url,
			"async" : false,
			"dataType" : "json",
			"data" : {
				"parentKey" : key
			},
			"success" : function(resp) {
				util.createOption(selectId, defaultOption, resp.dict);
			}
		});
    },
    
    /**
     * 创建下拉框选项
     * @param selectId 下拉框输入id
     * @param defaultOption 默认选择
     * @param resp 下拉框值
     */
    createOption: function(selectId, defaultOption, data) {
    	$("#"+selectId).empty();
		htmlStr = $("#"+selectId)[0].innerHTML;
		if(defaultOption !=undefined){
			if('请选择'==defaultOption){
				htmlStr +='<option value="" style="display:none">'+defaultOption+'</option>';
			} else {
				htmlStr +='<option value="" >'+defaultOption+'</option>';
			}
			
		}
		for (var i = 0; i < data.length; i++) {
			htmlStr += '<option value="' + data[i].dictKey + '">' + data[i].dictName + '</option>';
		}
		$("#"+selectId).append(htmlStr);
    },
    
    /**
     * 给下拉框赋值
     * @param url 下拉框数据查询方法
     * @param param 查询参数
     * @param selectId 下拉框ID
     */
    getOption:function(url, param, selectId) {
    	$.ajax({
			"type" : "post",
			"url" : url,
			"async" : false,
			"dataType" : "json",
			"data" : param,
			"success" : function(resp) {
				var data = [];
				data = resp.data;
				$("#" + selectId).find("option").not(":first").remove();
				var htmlStr = $("#" + selectId)[0].innerHTML;
				for (var i = 0; i < data.length; i++) {
					htmlStr += '<option value="' + data[i].key + '">' + data[i].value + '</option>';
				}
				$("#" + selectId).empty();
				$("#" + selectId).append(htmlStr);
			}
		});
    },
    
    /**
     * 给下拉框赋值
     * @param data 下拉框数据
     * @param selectId 下拉框ID
     */
    setOption:function(data, selectId) {
		$("#" + selectId).find("option").not(":first").remove();
		var htmlStr = $("#" + selectId)[0].innerHTML;
		for (var i = 0; i < data.length; i++) {
			htmlStr += '<option value="' + data[i].key + '">' + data[i].value + '</option>';
		}
		$("#" + selectId).empty();
		$("#" + selectId).append(htmlStr);
    },
    
    /**
     * 
     * @param Object对象
     * @returns 是否为空标志 true-空  false-非空
     */
    isEmptyObject:function(e) {  
        var t;  
        for (t in e)  
            return !1;  
        return !0;
    },
    
    /**
     * 初始化select2
     */
    initSelect:function(id,msg) {
    	if(msg == undefined){
    		msg = '请选择';
    	}
    	$(id).empty();
    	$(id).append('<option value=""></option>');
		//初始化所属客户下拉框
		$(id).select2({
      	     placeholder:msg,//默认文字提示
      	     language: "zh-CN",//汉化
      	     allowClear: true//允许清空
      	});
	},
	
	/**
	 * 
	 * @param id modal窗口的id
	 * @param content 提示内容
	 * @param yesId 确定按钮的id
	 */
	showModal:function(id, content, yesId) {
		$(id + " .btn.green").attr("id", yesId);
		$(id + " p").text(content);
		$(id).modal("show");
	},
	
	/**
	 * @param key 周期字典名
	 */
	getRefreshCycle:function(key){
		var cycle;
		$.ajax({
			"type" : "post",
			"url" : "main/sysDictIndex/getDictByParentKey.mvc",
			"async" : false,
			"dataType" : "json",
			"data" : {
				"parentKey" : key
			},
			"success" : function(resp) {
				if(resp.dict.length!=0){
					cycle = resp.dict[0].dictKey;
				}else {
					cycle = 25000;
				}
			}
		});
		return cycle;
	},
	
	/**
	 * 获取当前的日期时间 格式“yyyy-MM-dd HH:MM:SS”
	 * @return {}
	 */
	getNowFormatDate : function () {
		    var date = new Date();
		    var seperator1 = "-";
		    var seperator2 = ":";
		    var month = date.getMonth() + 1;
		    var strDate = date.getDate();
		    if (month >= 1 && month <= 9) {
		        month = "0" + month;
		    }
		    if (strDate >= 0 && strDate <= 9) {
		        strDate = "0" + strDate;
		    }
		    var hours = date.getHours();
		    if(hours >=0 && hours <=9){
		    	hours = "0" + hours;
		    }
		    var minutes = date.getMinutes();
		    if(minutes >=0 && minutes <=9){
		    	minutes = "0" + minutes;
		    }
		    var seconds = date.getSeconds();
		    if(seconds >=0 && seconds <=9){
		    	seconds = "0" + seconds;
		    }
		    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
		            + " " + hours + seperator2 + minutes
		            + seperator2 + seconds;
		    return currentdate;
	},

	/**
	 * [_initPackCodeSelect 初始化电池下拉框]
	 * @return {[type]} [description]
	 */
	initPackCodeSelect: function(divId,selectWidth) {
		$("#"+divId).select2({
			language: "zh-CN",
			allowClear: true,
			width: selectWidth||"175px",
			placeholder: "请选择",
			ajax: {
				url: "monitor/historyQuery/getPackCodeOptions2.mvc",
				dataType: 'json',
				delay: 250,
				data: function(params) {
					params.offset = 10;
					params.page = params.page || 1;
					return {
						name: params.term,
						page: params.page,
						offset: params.offset
					};
				},
				cache: false,
				processResults: function(res, params) {
					var users = res.data;
					var options = [];
					for (var i = 0, len = users.length; i < len; i++) {
						var option = {
							"id": users[i]["colClientId"],
							"text": (users[i]["serialNo"])
						};
						options.push(option);
					}
					return {
						results: options,
						pagination: {
							more: (params.page * params.offset) < res.total
						}
					};
				},
				escapeMarkup: function(markup) {
					return markup;
				},
				minimumInputLength: 1
			}
		});
	},

    initPackCodeSelect2: function(divId,selectWidth) {
        var select2 = $("#"+divId).select2({
            language: "zh-CN",
            allowClear: true,
            width: selectWidth||"175px",
            placeholder: "请选择",
            ajax: {
                url: "monitor/historyQuery/getPackCodeOptions2.mvc",
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    params.offset = 10;
                    params.page = params.page || 1;
                    return {
                        name: params.term,
                        page: params.page,
                        offset: params.offset
                    };
                },
                cache: false,
                processResults: function(res, params) {
                    var users = res.data;
                    var options = [];
                    for (var i = 0, len = users.length; i < len; i++) {
                        var option = {
                            "id": users[i]["colClientId"],
                            "text": (users[i]["serialNo"])
                        };
                        options.push(option);
                    }
                    return {
                        results: options,
                        pagination: {
                            more: (params.page * params.offset) < res.total
                        }
                    };
                },
                escapeMarkup: function(markup) {
                    return markup;
                },
                minimumInputLength: 1
            }
        });
        return select2;
    },


	/**
	 * [_initPackCodeSelect 初始化客户下拉框]
	 * @return {[type]} [description]
	 */
	initCustomerSelect: function(divId,selectWidth) {
		$("#"+divId).select2({
			language: "zh-CN",
			allowClear: true,
			width: selectWidth||"175px",
			placeholder: "请选择",
			ajax: {
				url: "main/customer/getCustomerOptions.mvc",
				dataType: 'json',
				delay: 250,
				data: function(params) {
					params.offset = 10;
					params.page = params.page || 1;
					return {
						name: params.term,
						page: params.page,
						offset: params.offset
					};
				},
				cache: false,
				processResults: function(res, params) {
					var users = res.data;
					var options = [];
					for (var i = 0, len = users.length; i < len; i++) {
						var option = {
							"id": users[i]["pkId"],
							"text": (users[i]["cusName"])
						};
						options.push(option);
					}
					return {
						results: options,
						pagination: {
							more: (params.page * params.offset) < res.total
						}
					};
				},
				escapeMarkup: function(markup) {
					return markup;
				},
				minimumInputLength: 1
			}
		});
	}
};